package com.jxw.scanpen;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;


import java.lang.ref.WeakReference;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class FunctionImpl {
    public final static short LANG_JA = 0; // 日文
    public final static short LANG_KO = 1; // 韩文
    public final static short LANG_YUE = 2; //粤语
    public final static short LANG_ZH = 3; // 中文
    public final static short LANG_EN = 4; // 英文
    public final static short LANG_TW = 5; // 繁体
    private IOcrAidlInterface mIFunInterface;

    String TAG = IOcrAidlInterface.class.getSimpleName();

    private CountDownLatch lock;

    private String packageName = "com.dosmono.sdk1";
    final String serviceName = "com.dosmono.sdk.ScanOcrService";

    private WeakReference<Context> appContext;
    private ServiceConnection serviceConnection;
    public static final int CONNECTION_PENDING = 1;

    public static final int ERROR_BINDING_FAILURE = 71;

    public static final int ERROR_OTHER = 500;
    private  ServiceListener listener = null;
    private ServiceCallback mCallback = null;

    public OcrCallback mActiveCallback = new OcrCallback.Stub() {
        @Override
        public void onResult(String ocr_result, boolean temp) throws RemoteException {
            if (mCallback != null) {
                mCallback.onResult(ocr_result,temp);
            }
        }

        @Override
        public void onSpeakTTSStart() throws RemoteException {
            if (mCallback != null) {
                mCallback.onSpeakTTSStart();
            }
        }

        @Override
        public void onSpeakTTSEnd() throws RemoteException {
            if (mCallback != null) {
                mCallback.onSpeakTTSEnd();
            }
        }

        @Override
        public void onSpeakTTSError() throws RemoteException {
            if (mCallback != null) {
                mCallback.onSpeakTTSError();
            }
        }

        @Override
        public void onTranslateResult(String trans) throws RemoteException {
            if (mCallback != null) {
                mCallback.onTranslateResult(trans);
            }
        }

        @Override
        public void onJpgResult(String path) throws RemoteException {
            if (mCallback != null) {
                mCallback.onJpgResult(path);
            }
        }


    };

    private static class TranslatorImplHelper {
        private static final FunctionImpl INSTANCE = new FunctionImpl();
    }

    public interface ServiceCallback {
        void onResult(String ocr_result, boolean temp);
        void onSpeakTTSStart();
        void onSpeakTTSEnd();
        void onSpeakTTSError();
        void onTranslateResult(String trans);
        void onJpgResult(String path);
    }

    public interface ServiceListener {
        void onConnected();
        void onDisconnected();
        void onDied();
    }

    public static FunctionImpl getInstance() {
        return TranslatorImplHelper.INSTANCE;
    }

    public void setServiceCallback(ServiceCallback mCallback) {
        this.mCallback = mCallback;
    }

    public int start(Context context,  ServiceListener listener,  ServiceCallback mCallback) {
        if (serviceConnection == null) {
            serviceConnection = new ServiceConnection();
        }

        this.appContext = new WeakReference<>(context.getApplicationContext());

        if (mIFunInterface == null) {

            lock = new CountDownLatch(1);

            this.listener = listener;
            this.mCallback = mCallback;

            Intent serviceIntent = new Intent()
                    .setComponent(new ComponentName(
                            packageName,
                            serviceName));

            if (appContext.get() == null) {
                return ERROR_OTHER;
            }
            boolean bindResult = appContext.get().bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);

            if (bindResult) {
                try {
                    boolean success = lock.await(10, TimeUnit.MILLISECONDS);
                    if (!success) {
                        return CONNECTION_PENDING;
                    }
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                    return CONNECTION_PENDING;
                }
            } else {
                return ERROR_BINDING_FAILURE;
            }
        }
        return ERROR_OTHER;
    }

    public void stop() {
        listener = null;
        if(mIFunInterface!=null)
            try {
                mIFunInterface.unregisterOcrCallback(mActiveCallback);

            } catch (Exception e) {
                e.printStackTrace();
            }
        if (appContext != null) {
            if (serviceConnection != null) {

                if (appContext.get() != null) {
                    appContext.get().unbindService(serviceConnection);
                }
                serviceConnection = null;
                mIFunInterface = null;
            }
        }

    }

    /**
     * ocr初始化
     * @param crop_left   左裁剪区域
     * @param crop_top    上裁剪区域
     * @param crop_right   右裁剪区域
     * @param crop_button 下裁剪区域
     * @param width    图片宽度
     * @param height   图片高度
     */
    public void initOcrSdk(int crop_left, int crop_top, int crop_right, int crop_button, int width, int height,boolean saveImage,boolean outText ) {
        if (mIFunInterface == null) {
            return ;
        }
        try {
            mIFunInterface.initOcrConfig(crop_left, crop_top,crop_right,crop_button,width,height,0,0,saveImage,outText);
        } catch (Exception e) {
            e.printStackTrace();

        }
        try {
            mIFunInterface.initOcrSdk(crop_left, crop_top,crop_right,crop_button,width,height,0,0);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }


    /**
     * 获得拼接图片
     *
     * @param data
     * @return
     */
    public void pushOcr(byte[] data, int status) {
        if (mIFunInterface == null) {
            return ;
        }
        try {
              mIFunInterface.pushOcr(data, status);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * 拼接引擎准备开始
     */
    public void SPOCREngineStart() {
        if (mIFunInterface == null) {
            return ;
        }
        try {
               mIFunInterface.SPOCREngineStart();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * 拼接引擎准备结束
     */
    public void SPOCREngineStop() {
        if (mIFunInterface == null) {
            return  ;
        }
        try {
              mIFunInterface.SPOCREngineStop();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public void getOCREngineResult() {
        if (mIFunInterface == null) {
            return ;
        }
        try {
            mIFunInterface.getOCREngineResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 合成TTS语音
     * @param lang 语言 	0; // 日文
     *                  1; // 韩文
     *                  2; //粤语
     * @param text 合成文本
     */
    public void playSound(int lang, String text) {
        if (mIFunInterface == null) {
            return  ;
        }
        try {
            mIFunInterface.playSound(lang,text);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * 停止TTS
     */
    public void stopSound(){
        if (mIFunInterface == null) {
            return  ;
        }
        try {
            mIFunInterface.stopSound();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * 判断TTS是否在播放
     */
    public boolean isSpeaking(){
        if (mIFunInterface == null) {
            return  false;
        }
        try {
            return mIFunInterface.isSpeaking();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  false;
    }

    /**
     * 设置TTS速度 0，1，2，3，4，5  （值越大播放速度越快）
     */
    public void setTTSSpeed(int speed){
        if (mIFunInterface == null) {
            return  ;
        }
        try {
            mIFunInterface.setTTSSpeed(speed);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * 翻译文本
     * 语言 	0; // 日文
     *      1; // 韩文
     *      2; //粤语
     *      3; // 中文
     *      4; // 英文
     *      5; // 繁体
     * @param srcLang  源语言
     * @param dstLang  目标语言
     * @param strInput
     * @return
     */
    public void getTranslateRes(int srcLang, int dstLang, String strInput){
        if (mIFunInterface == null) {
            return ;
        }
        try {
            mIFunInterface.getTranslateRes(srcLang,dstLang,strInput);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ;
    }

    public void initAEEEngine() {
        if (mIFunInterface == null) {
            return ;
        }
        try {
            mIFunInterface.initAEEEngine();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    private class ServiceConnection implements android.content.ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            Log.v(TAG, "onServiceConnected");
            mIFunInterface = IOcrAidlInterface.Stub.asInterface(service);
            try {
                mIFunInterface.registerOcrCallback(mActiveCallback);

            } catch (Exception e) {
                e.printStackTrace();
            }
            lock.countDown();

            if (listener != null) {
                listener.onConnected();
            }
        }

        @Override
        public void onBindingDied(ComponentName name) {
            Log.v(TAG, "onBindingDied");

            mIFunInterface = null;
            if (listener != null) {
                listener.onDied();
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName className) {
            Log.v(TAG, "onServiceDisconnected");

            mIFunInterface = null;
            if (listener != null) {
                listener.onDisconnected();
            }

            // This method is only invoked when the service quits from the other end or gets killed
            // Invoking exit() from the AIDL interface makes the Service kill itself, thus invoking this.
        }
    }


}
